package com.java2104.service;

import com.java2104.entity.Document;
import com.java2104.mapper.DocumentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DocumentService {
    @Autowired
    private DocumentMapper documentMapper;

    public Document get(Integer id){
        return documentMapper.findByPrimaryKey(id);
    }

    public Map getFileInputStream(Integer id) throws FileNotFoundException {
        Map map = new HashMap();
        Document doc = documentMapper.findByPrimaryKey(id);
        if(doc!=null){
            String filename = doc.getFilename();
            if(new File(DOCUMENT_SAVE_PATH).exists()){
                map.put("filename",filename);
                map.put("stream",new FileInputStream(DOCUMENT_SAVE_PATH + filename));
                return map;
            }
        }
        return null;
    }

    public List<Document> getList(String title){
        if(title!=null){
            title = title.trim();//把字符串中多余的空格去掉
        }
        return documentMapper.findByTitle(title);
    }
    //用于保存上传文档的路径
    public static final String DOCUMENT_SAVE_PATH = "D:/csi_oa_sys/doc/";

    public void save(Document document, MultipartFile multipart) throws IOException {
        //1.将记录存入数据库
        long timeMillis = System.currentTimeMillis();
        document.setCreateDate(new Timestamp(timeMillis));//设置创建时间
        //上传文件的原始名称，例如：xxx.doc
        document.setFilename(multipart.getOriginalFilename());
        documentMapper.insert(document);
        //2.将文件保存到服务器中
        if(! new File(DOCUMENT_SAVE_PATH).exists()){
            new File(DOCUMENT_SAVE_PATH).mkdirs();
        }
        String original = multipart.getOriginalFilename();
        //使用系统时间戳+原始文件后缀得到文件名
        String filename = original;
        //保存文件
        FileCopyUtils.copy(multipart.getInputStream(),new FileOutputStream(DOCUMENT_SAVE_PATH + filename));
    }

    public void update(Document document){
        documentMapper.updateByPrimaryKey(document);
    }

    public int delete(List<Integer> ids){
        return documentMapper.batchDelete(ids);
    }
}
